package com.kaibes.module.theme;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.kaibes.web.prefix.PrefixContext;
import com.kaibes.web.prefix.PrefixTarget;

@Component
public class ThemeStartedListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        
        ApplicationContext applicationContext = event.getApplicationContext();
        ThemeService themeService = applicationContext.getBean(ThemeService.class);
        PrefixContext prefixContext = applicationContext.getBean(PrefixContext.class);
        
        List<Theme> themeList = themeService.listActiveTheme();
        for (int i = 0; i < themeList.size(); i++) {
            Theme theme = themeList.get(i);
            PrefixTarget prefixTarget = new PrefixTarget();
            prefixTarget.setPrefix(theme.getUri()); //前缀路径
            prefixTarget.setTarget(theme.getPath()); //目标路径
            prefixContext.addPrefixTarget(prefixTarget);
        }
        
        //TODO
        /**
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(Controller.class);
        for (Object controller : beans.values()) {
            if (controller.getClass().isAnnotationPresent(Controller.class)) {
                RequestMapping mapping = controller.getClass().getDeclaredAnnotation(RequestMapping.class);
                if (mapping != null) {
                    String uri = mapping.value()[0];
                    if (uri.startsWith("/")&&uri.endsWith("/")) {
                        String[] strs = uri.split("/");
                        if (strs.length == 0) {
                            uri = "";
                        } else {
                            uri = strs[1];
                        }
                        if (!themeConfig.getUriList().contains(uri)) {
                            themeConfig.getUriList().add(uri);
                        }
                    }
                }
            }
        }**/
    }

}
